// pages/jianzhi/jianzhi.js
const db = wx.cloud.database().collection("zhanzuo")
Page({

  data: {
    listData: [],
    id:'',
    name: '',
    hao: ''
  },
  onShow: function () {
    this.getData ()
  },
  getData () { // 获取数据
    let thiss = this
    db.get({
      success (res) {
        console.log(res)
        thiss.setData({
          listData:res.data
        })
      }
    })
  },
  handleZhan (data) { // 修改数据
    wx.showLoading({
      title: "排队中...." ,
      mask: true,
    })
    this.setData ({
      hao:data.target.dataset.hao
    })
    const db = wx.cloud.database().collection("zhanzuo")
    let zhuangtai = ""
    let thiss = this
    if(data.target.dataset.zhuangtai === 'yong') {
      wx.showToast({
        title: '已被占座，请选择其它...',
        icon: 'none'
      })
    } else if(data.target.dataset.zhuangtai === 'gu') {
      wx.showToast({
        title: '故障，请选择其它...',
        icon: 'none'
      })
    } else if(data.target.dataset.zhuangtai === 'kong') {
      zhuangtai = 'yong'
      db.doc(data.target.dataset.id).update ({
        data: {
          zhuangtai:zhuangtai
        },
        success (res) {
          wx.hideLoading();
          wx.showToast({
            title: '占座成功...',
            icon: 'none'
          })
          console.log(res)
          thiss.getData()
          thiss.addData()
        },
        fail (err) {
          console.log(err)
        }
      })
    }
  },
  Getid(data){
    this.setData({
      id:data.detail.value
    })
  },
  Getname(data){
    this.setData({
      name:data.detail.value
    })
  },
  Time(){
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    //获取当前时间
    var n = timestamp * 1000;
    var date = new Date(n);
    var Y = date.getFullYear();
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var h = date.getHours();
    var m = date.getMinutes();
    var zong=Y+"年"+M+"月"+D+"日"+h+":"+m
    return zong
  },
  addData () { // 添加数据
    const db = wx.cloud.database().collection("zhanzuodan")
    db.add({
      data: {
        username:wx.getStorageSync("userInfo").nickName,
        hao:this.data.hao,
        time:this.Time()
      },
      success (res) {
        console.log(res)
      },
      fail (err) {
        console.log(err)
      }
    })
  }
})